<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <el-radio-group v-model="statusFilter" @change="handleFilterChange">
      <el-radio-button label="全部"></el-radio-button>
      <el-radio-button label="已上架"></el-radio-button>
      <el-radio-button label="未上架"></el-radio-button>
      <el-radio-button label="待审核"></el-radio-button>
      <el-radio-button label="未通过"></el-radio-button>
    </el-radio-group>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入价格" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="库存数量" prop="stock">
        <el-input v-model="queryParams.stock" placeholder="请输入库存数量" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="请输入品牌名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="规格" prop="spec">
        <el-input v-model="queryParams.spec" placeholder="请输入规格" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="销量" prop="sold">
        <el-input v-model="queryParams.sold" placeholder="请输入销量" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="评论数" prop="commentCount">
        <el-input v-model="queryParams.commentCount" placeholder="请输入评论数" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['shop:item:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['shop:item:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['shop:item:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['shop:item:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="mini" @click="handleShelf">上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="mini" @click="handleUnshelf">下架</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="filteredItemList"
      @selection-change="handleSelectionChange"
      :row-style="{ height: '60px' }"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品ID" align="center" prop="id" width="100"/>
      <el-table-column label="名称" align="center" prop="name" width="150"/>
      <el-table-column label="价格" align="center" prop="price" width="100"/>
      <el-table-column label="库存数量" align="center" prop="stock" width="100"/>
      <el-table-column label="商品图片" align="center" prop="image" width="120">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" align="center" width="100">
        <template slot-scope="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>      <el-table-column label="品牌名称" align="center" prop="brand" width="150"/>
      <el-table-column label="规格" align="center" prop="spec" width="150"/>
      <el-table-column label="销量" align="center" prop="sold" width="100"/>
      <el-table-column label="评论数" align="center" prop="commentCount" width="100"/>
      <el-table-column label="是否是推广广告" align="center" prop="isAD" width="120"/>
      <el-table-column label="商品状态" align="center" prop="status" :formatter="formatStatus" width="120"/>
      <el-table-column label="创建人" align="center" prop="creater" width="120"/>
      <el-table-column label="修改人" align="center" prop="updater" width="120"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['shop:item:edit']"
          >修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['shop:item:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父分类" style="display: inline-block; margin-right: 20px;">
          <el-select
            size="large"
            style="width: 240px"
            v-model="itemVo.subjectParentId"
            @change="selectChange"
            placeholder="请选择父分类"
          >
            <el-option
              v-for="item in subjects"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="子分类" style="display: inline-block;">
          <el-select
            size="large"
            style="width: 240px"
            v-model="form.categoryId"
            placeholder="请选择子分类"
          >
            <el-option
              v-for="item in childrenList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量"/>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="品牌名称" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌名称"/>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec" placeholder="请输入规格"/>
        </el-form-item>
        <el-form-item label="销量" prop="sold">
          <el-input v-model="form.sold" placeholder="请输入销量"/>
        </el-form-item>
        <el-form-item label="评论数" prop="commentCount">
          <el-input v-model="form.commentCount" placeholder="请输入评论数"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem, putItem,downItem } from '@/api/shop/item'
import { listSubject} from "@/api/shop/subject.js";
import { handleTree } from '@/utils/ruoyi'

export default {
  name: 'Item',
  data() {
    return {
      itemVo: {
        subjectParentId: '', // 选中的父分类 ID
        subjectId: '', // 选中的子分类 ID
      },
      subjects: [], // 父分类列表
      childrenList: [], // 子分类列表
      categoryList: [],
      statusFilter: '全部',
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      OldTotle:0,
      itemList: [],
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        price: null,
        stock: null,
        image: null,
        categoryId: null,
        brand: null,
        spec: null,
        sold: null,
        commentCount: null,
        isAD: null,
        status: null,
        creater: null,
        updater: null
      },
      form: {},
      rules: {
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
        stock: [{ required: true, message: '库存数量不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    filteredItemList() {
      if (this.statusFilter === '全部') {
        this.total = this.OldTotle
        return this.itemList;
      }
      const statusMap = {
        '已上架': 1,
        '未上架': 2,
        '待审核': 3,
        '未通过': 4
      };
      var filter = this.itemList.filter(item => item.status === statusMap[this.statusFilter])
      this.total = filter.length
      return filter;
    },
  },
  watch: {
    filteredItemList() {
      // this.getList()
      // 重置当前页码为第一页，确保切换筛选条件后从第一页开始显示
      this.currentPage = 1;
    }
  },
  created() {
    this.getList()
    this.loadCategories(); // 组件创建时加载类别数据
  },
  methods: {
    handleFilterChange() {
      // 筛选条件改变时触发
      this.queryParams.pageNum = 1
    },
    // 加载类别数据
    async loadCategories() {
      try {
        const response = await listSubject({}); // 调用类别列表接口
        this.subjects = handleTree(response.rows) || []; // 假设返回的数据在 response.rows 中
        this.categoryList = response.rows;
      } catch (error) {
        console.error('加载类别数据失败:', error);
      }
    },
    // 父分类选择变化时触发
    selectChange(parentId) {
      // 清空子分类的选择
      this.itemVo.subjectId = '';

      // 根据父分类 ID 查找对应的子分类
      const selectedParent = this.subjects.find(item => item.id === parentId);
      this.childrenList = selectedParent ? selectedParent.children || [] : [];
    },
    // 根据类别 ID 获取类别名称
    getCategoryName(categoryId) {
      const category = this.categoryList.find(item => item.id == categoryId);
      return category ? category.title : '未知类别';
    },
    // 加载商品数据
    // async getList() {
    //   if (this.subjects.length === 0) {
    //     await this.loadCategories(); // 如果类别数据未加载，先加载类别数据
    //   }
    //   this.loading = true;
    //   try {
    //     const response = await listItem({}); // 假设 listItem 是加载商品数据的方法
    //     this.itemList = response.rows || [];
    //   } catch (error) {
    //     console.error('加载商品数据失败:', error);
    //   } finally {
    //     this.loading = false;
    //   }
    // },
    formatStatus(row, column, cellValue) {
      switch (cellValue) {
        case 1:
          return '上架'
        case 2:
          return '下架'
        case 3:
          return '审核中'
        case 4:
          return '未通过'
        default:
          return '未知状态'
      }
    },
    handleShelf(row) {
      console.log('上架', row)
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认上架商品信息编号为"' + ids + '"的商品？').then(function() {
        return putItem(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('上架成功')
      }).catch(() => {
      })
    },
    handleUnshelf(row) {
      console.log('下架', row)
      console.log('下架', row)
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认下架商品信息编号为"' + ids + '"的商品？').then(function() {
        return downItem(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('下架成功')
      }).catch(() => {
      })
    },
    getList() {
      this.loading = true
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows
        this.total = response.total
        this.OldTotle = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        name: null,
        price: null,
        stock: null,
        image: null,
        categoryId: null,
        brand: null,
        spec: null,
        sold: null,
        commentCount: null,
        isAD: null,
        status: null,
        createTime: null,
        updateTime: null,
        creater: null,
        updater: null
      }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加商品信息'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改商品信息'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return delItem(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    handleExport() {
      this.download('shop/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px; /* 增加页面内边距 */
}

.el-table {
  margin-top: 20px; /* 表格与上方内容保持距离 */
}

.el-form-item {
  margin-bottom: 15px; /* 表单项之间的间距 */
}

.el-button {
  margin-right: 5px; /* 按钮之间的间距 */
}
</style>
